'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	if(event.coll_type == 0){
	// coll_type=0查看是否被此用户收藏
		let res = await add_remove(event);
		return res
	}else if(event.coll_type == 1){
	// coll_type=0用户点击收藏处理
		let res = await change_coll_status(event);
		return res
	}else if(event.coll_type == 2){
		let res = await select_coll(event);
		return res
	}
};

//查看是否被此用户收藏
const add_remove = async (event) => {
	const collection = db.collection('collection');
	let res = await collection.where({
		user_id: event.user_id,
		product_id: event.product_id,
		collection_type: 0
	}).count();
	if(res.total > 0){
		return true
	}else {
		return false
	}
}

//点击收藏
const change_coll_status = async (event) => {
	const collection = db.collection('collection');
	const product_detail = db.collection('product_Detail');
	let res = await collection.where({
		user_id: event.user_id,
		product_id: event.product_id,
		collection_type: 0
	}).count();
	if(res.total > 0){
		// 被收藏的话删除
		let result = await collection.where({user_id: event.user_id,product_id: event.product_id,collection_type: 0}).remove();
		return result
	}else {
		let result = await product_detail.where({_id:event.product_id}).get();
		let produce_info = result.data[0].produce_info;
		let product_activity = result.data[0].product_sale.activity_is;
		
		let params = {
			collection_activity: product_activity,
			collection_type : 0,
			product_id : result.data[0]._id,
			product_img_url: produce_info.product_important_img,
			product_title : produce_info.name,
			user_id: event.user_id,
			product_max_price: produce_info.product_max_price,
			product_min_price: produce_info.product_min_price
		};
		let save = await collection.add(params);
		return save
	}
}

//查看指定用户d的收藏
const select_coll = async (event) => {
	const collection = db.collection('collection');
	let res = await collection.where({
		user_id: event.user_id
	}).orderBy('create_time','desc').skip(event.pageNum * event.pageSize).limit(event.pageSize).get();
	return res
}